package com.tyqx.biz;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {

    @Value("${async.executor.corepoolsize}")
    private Integer corePoolSize;

    @Value("${async.executor.maxpoolsize}")
    private Integer maxPoolSize;

    @Value("${async.executor.queuecapacity}")
    private Integer queueCapacity;

    @Value("${async.executor.keepaliveseconds}")
    private Integer keepAliveSeconds;

    @Value("${async.executor.threadnameprefix}")
    private String threadNamePrefix;

    @Value("${async.executor.awaitterminationseconds}")
    private Integer awaitTerminationSeconds;

    /**
     * 线程池
     *
     * @return
     */
    @Bean(name = "asyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 基础线程数 corePoolSize: 10
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数 maxPoolSize: 500
        executor.setMaxPoolSize(maxPoolSize);
        // 队列长度 queueCapacity: 50
        executor.setQueueCapacity(queueCapacity);
        //  线程池维护线程所允许的空闲时间,单位为秒 keepAliveSeconds: 200
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程名字 threadNamePrefix: appasync
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        executor.initialize();
        return executor;
    }
}